define(["jquery","template","echarts","bbcare","comm/form/form.attention","comm/form/form.validate"],function($,template,echarts,$bb,$attention,$validate){
	var quest = {};
	var URL = $bb.baseUrl("followapp");

	/**
	 * tpl模板
	 */
	quest.tpl = function(){
		return 	'<script id="tpl_question_calc" type="text/html">'+
				'	<div {{if relationId}}relationId="{{relationId}}"{{/if}} class="qaCard form-group form-group-sm col-sm-{{length}} col-md-{{length}} grid-label-{{labelLength}}">'+
				'		<label class="control-label {{align}}">{{label}}</label>'+
				'   	<div class="control-input qaCard-inputGroup">'+ // qaCard-inputGroup 输入内容有icon的题型
				'			{{if status=="default"}}'+
				'   			<input type="text" class="form-control validatebox" name="{{name}}" data-calcType="{{calcType}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" placeholder="{{placeHolder}}" data-validate="{{validate}}" data-attention="{{attention}}" autocomplete="off">'+
				'				<div class="input-group-btn">'+
				'					<button type="button" class="btn btn-default">'+
				'						<i class="fa fa-area-chart"></i>'+
				'					</button>'+
				'				</div>'+
				'			{{else if status=="readonly"}}'+
				'				<p class="form-control-static validatebox" name="{{name}}" data-calcType="{{calcType}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" data-validate="{{validate}}" data-attention="{{attention}}"></p>'+
				'				<div class="input-group-btn">'+
				'					<button type="button" class="btn btn-default">'+
				'						<i class="fa fa-area-chart"></i>'+
				'					</button>'+
				'				</div>'+
				'			{{else if status=="disabled"}}'+
				'   			<input type="text" class="form-control validatebox" name="{{name}}" data-calcType="{{calcType}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" placeholder="{{placeHolder}}" data-validate="{{validate}}" data-attention="{{attention}}" disabled>'+
				'				<div class="input-group-btn">'+
				'					<button type="button" class="btn btn-default">'+
				'						<i class="fa fa-area-chart"></i>'+
				'					</button>'+
				'				</div>'+
				'			{{/if}}'+
				'		</div>'+
				'	</div>'+
				'</script>';
	}

	/**
	 * 赋值
	 */
	quest.setValue = function($dom,value){
		if( value ){
			if( $dom.hasClass("form-control-static") ){
				$dom.html(value.quesValue);
				$dom.trigger('DOMNodeInserted');
			}else{
				$dom.val(value.quesValue);
				$dom.trigger('input');
			}
		}
	}

	/**
	 * 获取value（保存时，获取每个dom对应的答案）
	 */
	quest.getValue = function($dom,name){
		var value = {};
		value.quesValue = $dom.hasClass("form-control-static") ? $dom.html() : $dom.val();
		value.quesId = $dom.attr("data-quesId");
		value.deCode = $dom.attr("data-deCode");
		value.innDeCode = $dom.attr("data-innDeCode");
		var dataUnit = $dom.attr("data-dataUnit");
		if( dataUnit ) value.dataUnit = dataUnit;
		return value;
	}

	/**
	 * 事件(若没有事件函数，可以不写)
	 * 		需要用到eventParams参数里的两个参数userId、gender、calcTestTime
	 */
	quest.event = function(eventParams,id){
		// qaCard-inputGroup为包裹带icon图标的input的div的class名;
		$("#"+ id +" .qaCard-inputGroup .input-group-btn").hide();
		$("#"+ id +" .qaCard-inputGroup input").bind("input propertychange",function(){
			var value = $(this).val();
			iconShowByVal($(this),value);
		});
		$("#"+ id +" .qaCard-inputGroup p.form-control-static").bind('DOMNodeInserted', function() {      
			var value = $(this).html();
			iconShowByVal($(this),value);
		});
		if( eventParams && eventParams.userId ){
            // 生成曲线
            if( eventParams.gender ){
                $("#"+ id +" .qaCard-inputGroup .input-group-btn button").unbind("click");
                $("#"+ id +" .qaCard-inputGroup .input-group-btn button").data({
                    "id":id,
                    "userId": eventParams.userId,
                    "testTime":eventParams.calcTestTime,
                    "gender":eventParams.gender,
                });
                $("#"+ id +" .qaCard-inputGroup .input-group-btn button").click(onGrowCurve);
            }
			// 百分位、日增长
            $("#"+ id +" .qaCard-inputGroup input").unbind("blur");
            $("#"+ id +" .qaCard-inputGroup input").data({
                "id":id,
                "userId": eventParams.userId,
                "testTime":eventParams.calcTestTime,
                "preNodeId":eventParams.preNodeId
            });
            $("#"+ id +" .qaCard-inputGroup input").blur(onGrowPercentile);
		}
	}

    /**
     * 提醒
     */
    quest.attention = function(id){
        $("#" + id + " .qaCard-inputGroup .validatebox").bind("blur input propertychange",onAttention);
        // 初始化
        $("#" + id + " .qaCard-inputGroup .validatebox").blur();
    }

    /**
     * 校验
     * flag:
     *   true:  (点击保存按钮时使用)
     *   false: 
     */
    quest.validate = function(id,flag){
        $("#" + id + " .qaCard-inputGroup .validatebox").bind("blur",onValidate);
        if( flag ){
            var result = true;
            $("#" + id + " .qaCard-inputGroup .validatebox").each(function(i){
                var params = {
                    "value":getValue($(this)),
                    "dom":$(this),
                    "flag":flag,
                };
                var success = $validate.init(params,handleByRuleValidate,handleBytypeValidate);
                result = result && success;
                if( !result ) return result;
            });
            return result;
        }
    }

	/******************** event begin ********************/
    /**
     * 百分位
     */
    var onGrowPercentile = function(){
        var data = $(this).data();
        var testTime = $bb.code.getValueByName(data.id,"taskSubmitDate");
        data.testTime = testTime ? testTime : data.testTime;
        var value = $(this).val();
        var dataUnit = $(this).attr("data-dataUnit");
        var calcType = $(this).attr("data-calcType");
        var deCode = $(this).attr("data-deCode");
        var percentilesName, growName, evaluation, deCodeList = [];
        deCodeList.push(deCode);
        switch( deCode ){
            case $bb.code.getDeCodeByName("weight"):
                percentilesName = $bb.code.getDeCodeNameByName("weightPercentiles");
                growName = $bb.code.getDeCodeNameByName("weightGrowth");
                evaluation = $bb.code.getDeCodeNameByName("weightEvaluation");
                break;
            case $bb.code.getDeCodeByName("height"):
                percentilesName = $bb.code.getDeCodeNameByName("heightPercentiles");
                growName = $bb.code.getDeCodeNameByName("heightGrowth");
                evaluation = $bb.code.getDeCodeNameByName("heightEvaluation");
                deCodeList.push($bb.code.getDeCodeByName("length"));
                break;
            case $bb.code.getDeCodeByName("length"):
                percentilesName = $bb.code.getDeCodeNameByName("lengthPercentiles");
                growName = $bb.code.getDeCodeNameByName("lengthGrowth");
                evaluation = $bb.code.getDeCodeNameByName("lengthEvaluation");
                deCodeList.push($bb.code.getDeCodeByName("height"));
                break;
            case $bb.code.getDeCodeByName("headSize"):
                percentilesName = $bb.code.getDeCodeNameByName("headSizePercentiles");
                growName = $bb.code.getDeCodeNameByName("headSizeGrowth");
                evaluation = $bb.code.getDeCodeNameByName("headSizeEvaluation");
                break;
        }
        var growPerDom = $(this).parents("form").find("input[name="+ percentilesName +"]");
        var lastGrowDom = $(this).parents("form").find("input[name="+ growName +"]");
        var evaluationDom = $(this).parents("form").find("input[name="+ evaluation +"]");
        if( value != "" ){
            if( calcType == "00001" && dataUnit == "g"){
                var n = $bb.simple.getDecimalPlaces(value) + 3;
                value = (value / 1000).toFixed(n);
            }
            var params = {
                "type": calcType,
                "userId": data.userId,
                "values": value,
                "testTime": data.testTime,
            };
            if( growPerDom || evaluationDom ) ajaxGrowthPercentiles(params,setPercentile,growPerDom,evaluationDom);
            var params2 = {
                "subBusiCode":"GROWTH",
                "ptNodeId":data.preNodeId,
                "userId": data.userId,
                "deCodeList":deCodeList,
            };
            var params3 = {
                "dom":lastGrowDom,
                "value":value,
                "testTime":data.testTime,
                "dataUnit":dataUnit,
                "deCode":deCode,
                "lastGrowDom":lastGrowDom,
            };
            if( lastGrowDom ) ajaxLastGrowth(params2,ajaxLastGrowthCallBack,params3);
        }else{
            if( growPerDom ) growPerDom.val("");
            if( lastGrowDom ) lastGrowDom.val("");
            if( evaluationDom ) evaluationDom.val("");
        }
    }
    /**
     * 请求百分位
     */
    var ajaxGrowthPercentiles = function(params,callback,growPerDom,evaluationDom){
        $bb.ajax({
            url: URL + "service/evaluation/growth/getGrowthPercentiles",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,growPerDom,evaluationDom);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "请求百分位出错");
                }
            }
        });
    }
    /**
     * 根据填入的身高、体重、头围填入百分位内容
     */
    var setPercentile = function(data,dom,dom2){
        dom.val(data.percentiles);
        dom2.val(data.sumary);
    }
    /**
     * 请求日增长
     */
    var ajaxLastGrowth = function(params2,callback,params3){
        $bb.ajax({
            url: URL + "ctrl/VaccineInfo/selectUserTaskValue",
            data: JSON.stringify({
                data: params2
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,params3);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "请求日增长出错");
                }
            }
        });
    }
    /**
     * 请求日增长成功后的回调函数
     */
    var ajaxLastGrowthCallBack = function(data,params3){
        var obj = getPreValue(data,params3);
        if( obj.quesValue ){ // 目前体重单位可配置kg、g;身高、身长、头围只可配置cm（若以后增加单位，需改代码）
            var result;
            var days = Number($bb.simple.dateDiff(obj.finishDate,params3.testTime).days);
            if( days > 0 ){
                if( obj.dataUnit == "g" ) obj.quesValue = Number(obj.quesValue) / 1000;
                result = (params3.value - obj.quesValue) / days; // 单位 kg
                var n = $bb.simple.getDecimalPlaces(params3.value) + 1;
                var dataUnit = params3.lastGrowDom.attr("data-dataUnit");
                if( dataUnit == "g" ){
                    result = result*1000;
                    n = n - 3 >= 0 ? n - 3 : 0;
                }
                result = result.toFixed(n);
                params3.lastGrowDom.val(result);
            }
        }
    }
    /**
     * 获取的上一次的答案的处理后的数据
     */
    var getPreValue = function(data,params3){
        if( data.rows.length > 0 ){
            for (var i = 0; i < data.rows.length; i++) {
                for (var j = 0; j < data.rows[i].length; j++) {
                    if( data.rows[i][j].deCode = params3.deCode ){
                        $.extend(data.rows[i][j],{"finishDate":data.ptTaskInfo.finishDate});
                        return data.rows[i][j];
                    }
                }
            }
            return {};
        }else{
            return {};
        }
    }

	/**
     * input输入框上的图标出现与否根据输入框内有无内容
     */
	var iconShowByVal = function(obj,value){
		if(value != ""){
			obj.parent(".qaCard-inputGroup").addClass("input-group");
			obj.next().show();
		}else{
			obj.parent(".qaCard-inputGroup").removeClass("input-group");
			obj.next().hide();
		}
	}
	/**
	 * 生长发育曲线 点击按钮弹出模态框
	 */
	var onGrowCurve = function(){
		var options = $(this).data();
		var $dom = $(this).parent().prev();
		var calcType = $dom.attr("data-calcType");
        var dataUnit = $dom.attr("data-dataUnit");
		var value = $dom.hasClass("form-control-static") ? $dom.html() : $dom.val();
        var testTime = $bb.code.getValueByName(options.id,"taskSubmitDate");
        testTime = testTime ? testTime : options.testTime ? options.testTime : $bb.simple.getCurTime().date;
		var label = $(this).parent().parent(".qaCard-inputGroup").prev().text(); //??
        if( calcType == "00001" && dataUnit == "g"){ // 体重要以kg进行保存
        	var keepDecimal = Math.pow(10,4);
        	value = Math.round(value / 1000 * keepDecimal) / keepDecimal;
        }
		var params = {
			scoreType:"01",	// 百分位曲线
			type: calcType,
			userId:	options.userId,
			values: value,
            testTime: testTime,
		};
		var className = "curveModal";
		$bb.modal({
			"className": className,
            "tit": "曲线图",
		},function(){
			growthCure(params,className,label,options.gender);
        });
	};
	/**
	 * 生长曲线图
	 */
	var growthCure = function(params,className,label,gender){
		ajaxGrowthCure(params,ajaxGrowthCureCallBack,className,label,gender);
	    $("."+ className).modal('show');
	}
	/**
     * 请求生长曲线图
     */
    var ajaxGrowthCure = function(params,callback,className,label,gender){
        $bb.ajax({
            url: URL + "service/evaluation/getGrowthCurvedataByValue",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,className,label,gender);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "请求生长曲线图出错");
                }
            }
        });
    }
    /**
	 * 请求生长曲线成功后的回调方法
	 */
    var ajaxGrowthCureCallBack = function(data,className,label,gender){
        curveUi(data,className,label,gender,1);
    }
	/**
     * 绘制曲线图
     */
	var curveUi = function(data,className,label,gender,interval){
		var divId = "chart-"+$bb.simple.random();
		var h = '<div id="'+ divId +'" class="curve"></div>';
		$("." + className + " .modal-body").html(h);

        if(data.curveType == "01"){ // growth曲线
            $("#"+divId).css({"height":470,"width":570});
            $("#"+divId).parents(".modal-content").css({"width":600});
        }else if(data.curveType == "02"){  // fenton曲线
            $("#"+divId).css({"height":855,"width": 570});
            $("#"+divId).parents(".modal-content").css({"width":600});
        }
        var myChart = echarts.init(document.getElementById(divId));
        var option = curveOption(data,interval,label,gender);
        myChart.setOption(option);
	}
	/**
     * 获取曲线图的参数
     */
    var curveOption = function(data,interval,label,gender){
        var option;
        if (data.scoreType == "01"){ // 百分位曲线
            if(data.curveType == "01"){ // growth曲线
                option = growthCurveOption(data.curvadataList[0].curvedata,label,interval,gender);
            }else if(data.curveType == "02"){  // fenton曲线
                option = fentonCurveOption(data,gender);
            }
        }
        return option;
    }
    /**
     * growth曲线图的参数
     */
    var growthCurveOption = function(curvedata,label,interval,gender){
        var sexColor = gender == 'F' ? "#e47db2":"#0596d5";
        var data = GrowthCurveTotalData(curvedata,label);
    	var option = {
        	backgroundColor: sexColor, //背景色
            textStyle: {
                fontSize: "15px",
                color:"#fff"
            },
            tooltip: {
                trigger: 'item',
                formatter: function (params) {
                    if(params.seriesName == "baby"){
                        var str = converAge(data.timeUnit,params.value[0],params.value[1],label);
                    }else{
                        var str = params.seriesName + ":" + params.value[1] + "<br />";
                    }                 
                    return str;
                }
            },
            legend: {
                data: []
            },
            grid: {
                left: '4%',
                right: '6%',
                bottom: '6%',
                top:'3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                name:data.xName,
                nameLocation:"middle",
                nameGap:"28",
                scale:true,
                boundaryGap: false,
                splitLine:{lineStyle:{color:"#eee"}}, //分隔线颜色
                splitArea : {show : false},//保留网格区域
                min:data.xMin,
                max:data.xMax,
                interval:interval,
                axisLine: {
                    lineStyle: {
                        color: "#8e7f8a"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    }
                },
                axisTick: {
                    show: false,
                    alignWithLabel: false,
                    interval: 'auto',
                    inside: true
                }
            },
            yAxis:{
                type: 'value',
                min:data.yMin,
                max:data.yMax,
                interval:data.interval,
                name:data.yName,
                nameLocation:"middle",
                nameGap:"28",
                splitLine:{lineStyle:{color:"#eee"}}, //分隔线颜色
                splitArea : {
                    show :true,//保留网格区域
                    areaStyle:{
                        color:"#fff"
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: "#8e7f8a"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    }
                },
                axisTick: {
                    show: false,
                    alignWithLabel: false,
                    inside: true
                }
            },
            series: seriesParams(data,sexColor),
        };
        return option;
    }
    /**
	 * 生长曲线数据处理(整体)
	 */
    var GrowthCurveTotalData = function(data,label){
        var obj = {};
        obj.xMax = data.xMax;
        obj.xMin = data.xMin;
        obj.yMax = data.yMax;
        obj.yMin = data.yMin;
        var len = parseInt((obj.yMax - obj.yMin) / 25);		// 自定义y轴间距
        for (var i = 0; i <= len; i++) {
        	if(i == len){
        		obj.interval = i+1;
        	}
        }
        if(data.timeUnit == "周"){							// x轴名称
            obj.xName = "周龄（0-"+ data.xMax +"周)";
            obj.timeUnit = "周";
        }else if(data.timeUnit == "月"){
            obj.xName = "月龄（0-"+ data.xMax +"月)";
            obj.timeUnit = "月";
        }else if(data.timeUnit == "年"){
            obj.xName = "年龄（0-"+ data.xMax +"岁)";
            obj.timeUnit = "年";
        }
        obj.yName = label.replace(/\(g\)/,"(kg)");			// y轴名称
        /* 曲线数组 */
        var numArr = [0,1,1,2,2,3,3];  // 线的颜色下标
        var colors = ['#00843d','#ff860d','#e41836','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        var nameArr = ["50%","75%","25%","90%","10%","97%","3%"];
        var dataSDArr = [data.SD0,data.SD1,data.SD1eng,data.SD2,data.SD2eng,data.SD3,data.SD3eng];
        var sdArr = [];
        for(var i=0; i<dataSDArr.length; i++){
            sdArr[i] = {
                "num" : numArr[i],
                "name" : nameArr[i],
                "sd" : growthCurveNormData(dataSDArr[i], data.xMax, data.xMin, nameArr[i], colors[numArr[i]])
            }
        }
        obj.sd = sdArr;
        obj.grownRecord = growthCurvePresentData(data.growthrecord);
        return obj;
    }
    /**
	 * 生长曲线数据处理(每一条)
	 */
    var growthCurveNormData = function(data,max,min, name, color){
    	var arr = [];
        var lens = data.length;
        var len = (max - min) / lens;
        arr[0] = [0, data[0]];
        for(var i = 0; i < lens; i++){
           if(i == lens-1 ){
                var lastData = {
                    value: [len*(i+1)+min, data[i]],
                    label : {
                        normal:{
                            show: true,
                            position: "insideBottomLeft",
                            textStyle : {
                                color:color,
                                fontSize:"8"
                            },
                            formatter: name                        
                        }
                    },
                };
                arr[i+1] = lastData;
           }else{
                arr[i+1] = [len*(i+1)+min, data[i]];
           }
       	}
        return arr;
    }
    /**
     * 患者传入记录值数据处理
     */
    var growthCurvePresentData = function(data){
        var arr = [];
        for(var i = 0; i < data.length; i++){
            if(data[i].flag == "1"){
                var recentGrowthRecord = {
                    value: [data[i].xDate, data[i].yDate],
                    symbol: 'circle',
                    symbolSize : 20,
                    itemStyle: {        // 数据级个性化折线样式
                        normal: {
                            color: 'yellowgreen',
                        },
                        emphasis: {
                            color: 'orange',
                            label : {
                                show: true,
                                position: 'inside',
                                textStyle : {
                                    fontSize : '18'
                                }
                            }
                        }
                    }
                };
                arr.push(recentGrowthRecord);
            }else{
                arr.push([data[i].xDate, data[i].yDate]);
            }
        }
        return arr;
    }
    /**
     * 曲线图中转换年龄
     */
    var converAge = function(timeUnit,value0,value1,label){
        var allDays;
        if(timeUnit ==="周"){
            allDays = value0*7;
            var weeks = Math.floor(allDays/7);
            var days = Math.round(allDays%7);
            var age = weeks + "周" + days + "天";
        }else if(timeUnit=="月"){
            allDays = value0*30.4;
            var months = Math.floor(allDays/30.4);
            var days = Math.floor(allDays%30.4);
            var age = months + "月" + days + "天";
        }else if(timeUnit=="年"){
            allDays = value0*365;
            var years = Math.floor(allDays/365);
            var months = Math.floor(allDays%365/30.4);
            var days = Math.round(allDays%365%30.4);
            var age = years + "岁" + months + "月" + days + "天";
        }
        var labelUnit = label.split("(");
        var unit = labelUnit[1].split(")")[0];
        if (unit == "g") {
            unit = "kg";
        }
        var str = timeUnit+"龄：" + age + "<br />" + 
                  labelUnit[0] + "：" + value1 + unit +"<br />";
        return str;
    }
    /**
     * 曲线图中数据参数
     */
    var seriesParams = function(data,sexColor){
        var colors = ['#12aa59','#ffb13d','#e76b7d','#6d555b'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        var series = [];
        for (var i = 0; i < data.sd.length; i++) {
            series.push({
                name: data.sd[i].name,
                type: 'line',
                smooth:"true",
                symbol:'circle',
                hoverAnimation:false,
                data: data.sd[i].sd,
                itemStyle: {
                    normal: {
                        color: "transparent",
                        lineStyle: {
                            color: colors[data.sd[i].num],
                            width:0.5
                        },
                    }
                }
            });
        };
        series.push({
            name: 'baby',
            type: 'line',
            data:data.grownRecord,
            symbol:'circle',
            symbolSize:'10',
            itemStyle: {
                normal: {
                    color: sexColor,
                    lineStyle: {
                        width: 3
                    }
                },
            },
        });
        return series;
    }
    /**
     * fenton曲线图的参数
     */
    var fentonCurveOption = function(data,gender){
        var sex = gender == 'F' ? "女":"男"; 
        var sexColor = gender == 'F' ? "#e47db2":"#0596d5";
        var series = fentonData(data,sexColor,sex);
        var option = {
            backgroundColor: sexColor, //背景色
            tooltip: {
                formatter: function( params, ticket, callback ) {
                    var val = "";
                    if(params.seriesName == "体重" || params.seriesName == "身长" || params.seriesName == "头围"){
                        if(params.componentType != "markPoint") {
                            var gestationAge = parseInt(params.data.value[0] / 7) + "周" + Math.round(params.data.value[0] % 7) + "天";
                            var value = params.seriesName == "体重" ? parseFloat(params.data.value[1]).toFixed(2) : parseFloat(params.data.value[1]).toFixed(1);
                            val += "胎龄：" + gestationAge + "<br/>" + params.seriesName + "：" + value;
                        }
                    }else{
                        var dataY = params.data instanceof Array ? params.data[1] : params.data.value[1];
                        val += params.seriesName +": "+ parseFloat(dataY).toFixed(3);
                    }
                    return val;
                }
            },
            grid: {
                left: '0%',
                right: '0%',
                bottom: '4%',
                top:'3%',
                containLabel: true
            },
            xAxis: {
                name: '胎龄（周）',
                nameLocation: 'middle',
                nameGap:"27",
                nameTextStyle: {color: "#fff"},
                max:50,
                min:22,
                interval:1,
                splitLine:{     //网格线
                    show: true,
                    lineStyle:{
                        color:["#333","#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc", "#333","#ccc","#ccc",
                                "#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc"]
                    }
                },
                splitArea : {show : false},//保留网格区域
                axisTick: {
                    show: true,
                    alignWithLabel: false,
                    interval: 'auto',
                    inside: true
                },
                axisLabel: {
                    textStyle: {
                        color: function(value){
                            if(value%2 != 0){
                                return "transparent";
                            }else{
                                return "#fff";
                            }
                        }
                    }
                },
            },
            yAxis: [
                {
                    name: '体重(kg)                                              厘米',
                    nameLocation: 'middle',
                    nameGap:"30",
                    nameTextStyle: {color: "#fff"},
                    max: 9,
                    min:0,
                    interval:0.1,
                    type: 'value',
                    splitLine:{
                        show: true//保留网格线
                    },
                    splitArea : {
                        show :true,//保留网格区域
                        areaStyle:{
                            color:"#fff"
                        }
                    },
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value > 4 ? "transparent" : value * 10 % 5 != 0 ? "transparent" : "#fff";
                            }
                        }
                    },
                },
                {
                    name:'体重(kg)                                              厘米',
                    nameLocation: 'middle',
                    nameGap:"27",
                    nameTextStyle: {color: "#fff"},
                    type: 'value',
                    max: 60,
                    min:-30,
                    interval:1,
                    splitLine:{
                        show: true//保留网格线
                    },
                    splitArea : {
                        show :true,//保留网格区域
                        areaStyle:{
                            color:"#fff"
                        }
                    },
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value < 40 ? "transparent" : value % 5 != 0 ? "transparent" : "#FFF";
                            }
                        }
                    }
                },
                {
                    position:'left',
                    type: 'value',
                    max: 60,
                    min:-30,
                    interval:1,
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value < 15 ? "transparent" : value % 5 != 0 ? "transparent" : "#FFF";
                            }
                        }
                    }
                },
                {
                    type: 'value',
                    position:'right',
                    max: 9,
                    min:0,
                    interval:0.1,
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return value > 6.5 ? "transparent" : value * 10 % 5 != 0 ? "transparent" : "#FFF";
                            }
                        }
                    },
                    splitLine:{
                        show: true,//保留网格线
                        lineStyle:{
                            color:["#333","#ccc","#ccc","#ccc","#ccc"],
                            width:1
                        }
                    }
                }
            ],
            animation:false,
            series:series
        };
        return option;
    }
    /**
     * fenton曲线数据处理
     */
    var fentonData = function(data,sexColor,gender){
        var fentonRes = {};
        var keyName = ["weight","height","head"];
        var keyName2, lineType, lineColor;
        if(data.scoreType == "01"){
            keyName2 = ['50%','10%','90%','3%','97%','baby'];
            lineType = ['solid','dashed','dashed','dotted','dotted'];
            lineColor=['#00612d','#00b0c8','#00b0c8','#ff8400','#ff8400'];
            for( var i = 0; i < data.curvadataList.length; i++ ){
                if( data.curvadataList[i].type == '0000'+(i+1) ){
                    fentonRes[keyName[i]] = [];
                    fentonRes[keyName[i]][0] = data.curvadataList[i].curvedata.SD0,
                    fentonRes[keyName[i]][1] = data.curvadataList[i].curvedata.SD2eng,
                    fentonRes[keyName[i]][2] = data.curvadataList[i].curvedata.SD2,
                    fentonRes[keyName[i]][3] = data.curvadataList[i].curvedata.SD3eng,
                    fentonRes[keyName[i]][4] = data.curvadataList[i].curvedata.SD3,
                    fentonRes[keyName[i]][5] = data.curvadataList[i].curvedata.growthrecord
                }
            }
        }else if(data.scoreType == "02"){
            keyName2 = ['0','-1','1','-2','2','-3','3','baby'];
            lineType = ['solid','solid','solid','solid','solid','solid','solid'];
            lineColor = ['#00612d','#ffb13d','#ffb13d','#e41836','#e41836','#252122','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
            for( var i = 0; i < data.curvadataList.length; i++ ){
                if( data.curvadataList[i].type == '0000'+(i+1) ){
                    fentonRes[keyName[i]] = [];
                    fentonRes[keyName[i]][0] = data.curvadataList[i].curvedata.SD0,
                    fentonRes[keyName[i]][1] = data.curvadataList[i].curvedata.SD1eng,
                    fentonRes[keyName[i]][2] = data.curvadataList[i].curvedata.SD1,
                    fentonRes[keyName[i]][3] = data.curvadataList[i].curvedata.SD2eng,
                    fentonRes[keyName[i]][4] = data.curvadataList[i].curvedata.SD2,
                    fentonRes[keyName[i]][5] = data.curvadataList[i].curvedata.SD3eng,
                    fentonRes[keyName[i]][6] = data.curvadataList[i].curvedata.SD3,
                    fentonRes[keyName[i]][7] = data.curvadataList[i].curvedata.growthrecord
                }
            }
        }
        var series = [];
        for(var key in fentonRes){
            var name, yAxisIndex, type;
            name = key == 'height' ? "身长" : key == 'weight' ? "体重" : key == 'head' ? "头围" : "baby";
            yAxisIndex = key == 'weight' ? 0 : 1;
            for( var i = 0; i < fentonRes[key].length; i++ ){
                if( i == fentonRes[key].length-1 ){
                    var params = {
                        'growthrecord':fentonRes[key][i],
                        'sex':gender,
                        'scoreType':data.scoreType,
                        'curveType':data.curveType
                    };
                    var babyInit = growthRecordDeal(params);
                    babyInit.nowFlag[1] = key == 'weight'? parseFloat(babyInit.nowFlag[1]).toFixed(2) : parseFloat(babyInit.nowFlag[1]).toFixed(1);
                    var baby = {
                        name: name,
                        type: 'line',
                        data: babyInit.history,
                        symbol:'circle',
                        symbolSize:'6',
                        markPoint: {
                            itemStyle: {
                                normal: {
                                    color:babyInit.nowFlag[2]
                                }
                            },
                            data: [
                                {
                                    xAxis: babyInit.nowFlag[0],
                                    yAxis: babyInit.nowFlag[1] 
                                }
                            ]
                        },
                        itemStyle: {
                            normal: {
                                color: sexColor,
                                lineStyle:{
                                    width:1
                                }
                            },
                            emphasis:{
                                color: sexColor
                            }
                        },
                        yAxisIndex: yAxisIndex
                    }
                    series.push(baby);
                }else{
                    fentonRes[key][i] = trendsNameDeal(fentonRes[key][i],keyName2[i],name,lineColor[i]);
                    var trend = {
                        name: keyName2[i],
                        type: 'line',
                        smooth:"true",
                        symbol:'circle',
                        hoverAnimation:false,
                        itemStyle: {
                            normal: {
                                color: "transparent",
                                lineStyle: {
                                    color:lineColor[i],
                                    type:lineType[i],
                                    width:1
                                }
                            }
                        },
                        data: fentonRes[key][i],
                        yAxisIndex:yAxisIndex
                    }
                    series.push(trend);
                }
            }
        }
        series.push({
            type: 'line',
            smooth:"true",
            symbol:'circle',
            hoverAnimation:false,
            lineStyle: {
                normal: {
                    color:"#333",
                    type:"solid",
                    width:2
                }
            },
            data: [[40,-30],[40,60]]
        });
        return series;
    }
    //儿童传入记录值数据处理：
    var trendsNameDeal=function(data,name,trendname,color){
        var len=data.length;
        data[len-24]={
            value: data[len-24],
            label : {
                normal:{
                    show: true,
                    position: "insideRight",
                    textStyle : {
                        color:color,
                        fontSize:"9"
                    },
                    formatter:name
                }
            },
        }
        if(name=="97%" || name=="3"){
            data[len-55]={
                value: data[len-55],
                label : {
                    normal:{
                        show: true,
                        position: 'top',
                        textStyle : {
                            color:"#aaa",
                            fontSize:"8"
                        },
                        formatter:trendname
                    }
                },
            }
        }
        return data;
    }
    /**
     * fenton数据（点数据）记录处理
     */
    var growthRecordDeal = function(data){
        var initArr = {
            "history":[],
            'nowFlag':[]
        };
        var color = ["#0596d5","#e47db2","#ff8400"];//0,男；1，女；3，橙色
        var list = data.growthrecord;
        for( var i = 0; i < list.length; i++ ){
            if( list[i].result ) {
                if (data.scoreType == "01") {
                    // var result = JSON.parse(list[i].result)[0].percentileRange;  // 可以直接用这行代替下面的判断
                    if(typeof list[i].result == "string"){
                        var result = JSON.parse(list[i].result)[0].percentileRange;
                    }else{
                        var result = list[i].result[0].percentileRange;
                    }

                    if(data.curveType == "02"){
                        if (result.indexOf("~") != "-1") {
                           var sexColor = data.sex == "男" ? color[0] : color[1];
                        }else{
                           var sexColor = color[2];
                        }
                    }
                }
            }
            var fentonRecord = {
                value: [list[i].xDate,list[i].yDate],
                itemStyle: {
                    normal:{
                        color:sexColor
                    },
                    emphasis: {
                        color: sexColor
                    }
                }
            };
            initArr.history.push(fentonRecord);
            if(list[i].flag == "1" || list[i].flag == 1){ // list[i].flag == "1"可以删掉
                initArr.nowFlag = [list[i].xDate,list[i].yDate,sexColor];
            }
        }
        return initArr;
    };

    /******************** event end ********************/

    /**
     * 获取输入的值(validate、attention中需要用到)
     */
    var getValue = function($dom){
        var value = $dom.hasClass("form-control-static") ? $dom.html() : $dom.val();
        return value.trim();
    }

    /********************  attention begin  ********************/

    /**
     * xx情况下触发的事件 (有可能是失去焦点等)
     */
    var onAttention = function(){
        var params = {
            "value":getValue($(this)),
            "dom":$(this),
        };
        $attention.init(params,handleByRule,handleBytype);
    }

    /**
     * 根据单个规则rule获取单个规则的结果result
     * 该题型已有规则在case里拦截，公用规则从default里返回结果
     * @return Boolean [布尔值]
     */
    var handleByRule = function(obj){
        var result;
        switch(obj.type) {
            default:
                result = $attention.handleByRule(obj);
        }
        return result;
    }

    /**
     * 根据提醒类型(type)执行对应的方法
     * 该题型已有提醒类型在case里拦截，公用提醒类型在default里处理
     */
    var handleBytype = function(obj){
        if( obj.type ){
            switch(obj.type) {
                default:
                    $attention.handleBytype(obj);
            }
        }
    }

    /********************  attention end  ********************/

    /********************  validate begin  ********************/

    /**
     * xx情况下触发的事件 (有可能是失去焦点等)
     */
    var onValidate = function(){
        var params = {
            "value":getValue($(this)),
            "dom":$(this),
        };
        $validate.init(params,handleByRuleValidate,handleBytypeValidate);
    }

    /**
     * 根据单个规则rule获取单个规则的结果result
     * 该题型已有规则在case里拦截，公用规则从default里返回结果
     * @return Boolean [布尔值]
     */
    var handleByRuleValidate = function(obj){
        var result = true;
        switch(obj.type) {
            default:
                result = $validate.handleByRule(obj);
        }
        return result;
    }

    /**
     * 根据提醒类型(type)执行对应的方法
     * 该题型已有提醒类型在case里拦截，公用提醒类型在default里处理
     */
    var handleBytypeValidate = function(obj){
        if( obj.type ){
            switch(obj.type) {
                default:
                    $validate.handleBytype(obj);
            }
        }
    }

    /********************  validate begin  ********************/

	return quest;
});